package com.three.system.service.impl;


import com.three.core.entity.Menu;
import com.three.system.mapper.MenuMapper;
import com.three.system.service.MenuService;
import com.three.core.vo.R;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public R<List<Menu>> getByUserId(Integer userId) {
        List<Menu> menus = menuMapper.selectByUserId(userId);
        return new R<List<Menu>>(200,"查询成功",menus);
    }

    @Override
    public R<List<Menu>> leftMenu() {
        // 获取 Token
        String token = request.getHeader("token");
        // 获取用户名
        Object user = redisTemplate.opsForHash().get("user::login::" + token, "name");
        if (user == null) {
            return new R<>(401, "用户未登录", null);
        }

        // 根据用户名查询权限菜单
        List<Menu> menus = menuMapper.selectMenusByUserName((String) user);

        // 去重
        menus = menus.stream()
                .distinct()
                .collect(Collectors.toList());

        // 查询一级菜单 (parentId == 0)
        List<Menu> firstMenus = menus.stream()
                .filter(menu -> menu.getParentId() == 0)
                .collect(Collectors.toList());

        // 为每个一级菜单设置子菜单
        for (Menu firstMenu : firstMenus) {
            List<Menu> childMenus = menus.stream()
                    .filter(menu -> firstMenu.getMenuId().equals(menu.getParentId()))
                    .collect(Collectors.toList());
            firstMenu.setChildren(childMenus);
        }

        return new R<>(200, "查询成功", firstMenus);
    }
}
